#include "TcpServer.hpp"
#include "Comm.hpp"
#include "Thanslate.hpp"
#include "Daemon.hpp"
#include <memory>
#include <cctype>
#include <algorithm>

using namespace std;

Translate trans;

void Usage(std::string proc)
{
    std::cout << "Usage : \n\t" << proc << " local_port\n"
              << std::endl;
}

void interact(int sockfd, string& out, const string &in)
{
    char buffer[1024];
    ssize_t n = read(sockfd, buffer, sizeof(buffer)-1);
    if(n > 0){
        buffer[n] = 0;
        write(sockfd, in.c_str(), in.size());
    }
    else if (n == 0) // read如果返回值是0，表示读到了文件结尾(对端关闭了连接！)
    {
        lg.LogMessage(Info, "client quit...\n");
    }
    else
    {
        lg.LogMessage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
    }
}
void Ping(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd : %d\n", addr.PrintDebug().c_str(), "ping", sockfd);
    string message;
    interact(sockfd, message, "Pong");
}

void translate(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd : %d\n", addr.PrintDebug().c_str(), "Translate", sockfd);
    // std::string word;
    char wordbuf[128];
    int n = read(sockfd, wordbuf, sizeof(wordbuf)-1);
    if(n > 0)
    {
        wordbuf[n] = 0;
    }
    string Chinese = trans.Excute(wordbuf);
    write(sockfd, Chinese.c_str(), Chinese.size());
    
    lg.LogMessage(Debug, "%s Translate service, %s->%s\n", addr.PrintDebug().c_str(), wordbuf, Chinese.c_str());
}
// 改成大写，字符串改成大写
void Transform(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd : %d\n", addr.PrintDebug().c_str(), "Transform", sockfd);
    char message[1024];
    ssize_t n = read(sockfd, message, sizeof(message) - 1);
    if(n > 0) message[n] = 0;
    std::string messagebuf = message;//                            _result   
    std::transform(messagebuf.begin(), messagebuf.end(), messagebuf.begin(), [](unsigned char c){
        return std::toupper(c);
    });
    write(sockfd, messagebuf.c_str(), messagebuf.size());
}   

int main(int argc, char* argv[])
{
    if(argc != 2){
        Usage(argv[1]);
        return 1;
    }
    //string serverip = argv[1];
    uint16_t serverport = stoi(argv[1]);
    daemon(false, false);
    lg.Enable(ClassFile);
    std::unique_ptr<TcpServer> tsvr = make_unique<TcpServer>(serverport);
    
    tsvr->RegisterFunc("ping", Ping);
    tsvr->RegisterFunc("translate", translate);
    tsvr->RegisterFunc("transform", Transform);
    tsvr->Init();



    tsvr->Start();

    return 0;

}